package com.cugmarket.controller.product.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cugmarket.dto.Result;
import com.cugmarket.entity.ProductCollect;
import com.cugmarket.service.ProductCollectService;
import com.cugmarket.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static com.cugmarket.constant.MessageConstant.*;

@Slf4j
@RestController
@RequestMapping("/user/productCollect")
public class ProductCollectController {
    @Resource
    private ProductCollectService productCollectService;

    /**
     * 新增收藏
     * @param productCollect
     * @return
     */
    @PostMapping("/add")
    @Transactional
    public Result add(@RequestBody ProductCollect productCollect) {
        // 判断商品ID是否为空
        if(productCollect.getProductId() == null) {
            return Result.error(INSERT_ERROR);
        }
        Boolean saved = productCollectService.addProductCollect(productCollect);
        if (!saved) {
            return Result.error(INSERT_ERROR);
        }
        return Result.success(INSERT_SUCCESS);
    }

    /**
     * 根据商品ID查询是否已经被当前用户收藏
     * @return
     */
    @GetMapping("/isCollect")
    public Result isCollect(@RequestParam ("productId") String productId) {
        String userId = UserHolder.getUser();
        LambdaQueryWrapper<ProductCollect> queryWrapper = new LambdaQueryWrapper<ProductCollect>().
                eq(ProductCollect::getUserId, userId)
                .eq(ProductCollect::getProductId, productId);
        ProductCollect productCollect = productCollectService.getOne(queryWrapper);
        if (productCollect == null) {
            return Result.success(false);
        }
        return Result.success(true);
    }

    /**
     * 删除收藏
     * @param productId
     * @return
     */
    @DeleteMapping("/delete")
    @Transactional
    public Result delete(@RequestParam("productId") String productId) {
        if (productId == null) {
            return Result.error(DELETE_ERROR);
        }
        Boolean removed = productCollectService.removeProductCollect(productId);
        if (!removed) {
            return Result.error(DELETE_ERROR);
        }
        return Result.success(UPDATE_SUCCESS);
    }

    /**
     * 获取用户收藏列表
     * @return
     */
    @GetMapping("/list")
    public Result<List<ProductCollect>> list() {
        String userId = UserHolder.getUser();
        List<ProductCollect> productCollects = productCollectService.getPCByUserId(userId);
        return Result.success(productCollects);
    }
}
